import { css } from './styles.js';
import { render } from './html.js';
import { 
    bindEvents, 
    handleAction, 
    toggleLike, 
    toggleCollect, 
    openComments, 
    openShare, 
    triggerAnimation, 
    formatCount 
} from './scripts.js';

class InteractionBar extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        
        // 初始化状态
        this.state = {
            liked: false,
            collected: false,
            likeCount: parseInt(this.getAttribute('like-count') || '0'),
            commentCount: parseInt(this.getAttribute('comment-count') || '0'),
            collectCount: parseInt(this.getAttribute('collect-count') || '0'),
            shareCount: parseInt(this.getAttribute('share-count') || '0')
        };

        this.render();
        this.bindEvents();
    }

    render() {
        this.shadowRoot.innerHTML = `
            <style>${css}</style>
            ${render(this.state)}
        `;
    }

    bindEvents() {
        bindEvents(this.shadowRoot, this.state, this);
    }

    handleAction(action, element) {
        handleAction(action, element, this.state, this);
    }

    toggleLike(element) {
        toggleLike(element, this.state, this);
    }

    toggleCollect(element) {
        toggleCollect(element, this.state, this);
    }

    openComments() {
        openComments(this.state, this);
    }

    openShare() {
        openShare(this.state, this);
    }

    triggerAnimation(element, type) {
        triggerAnimation(element, type);
    }

    formatCount(count) {
        return formatCount(count);
    }

    // 属性变化监听
    static get observedAttributes() {
        return ['like-count', 'comment-count', 'collect-count', 'share-count'];
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if (oldValue !== newValue) {
            switch (name) {
                case 'like-count':
                    this.state.likeCount = parseInt(newValue || '0');
                    break;
                case 'comment-count':
                    this.state.commentCount = parseInt(newValue || '0');
                    break;
                case 'collect-count':
                    this.state.collectCount = parseInt(newValue || '0');
                    break;
                case 'share-count':
                    this.state.shareCount = parseInt(newValue || '0');
                    break;
            }
            this.render();
            this.bindEvents();
        }
    }
}

window.customElements.define('interaction-bar', InteractionBar);